<template>
    <form>
        <h1>新增图书</h1>
        <table>
            <tr>
                <td>图书名称：</td>
                <td><input type="text" v-model="book.bookName" /></td>
            </tr>

            <tr>
                <td>作者：</td>
                <td><input type="text" v-model="book.autor" /></td>
            </tr>

            <tr>
                <td>价格：</td>
                <td><input type="text" v-model="book.price" /></td>
            </tr>

            <tr>
                <td colspan="2">
                    <input type="reset" value="清空" />
                    <input type="button" value="新增" @click="add" />
                    <input type="button" value="取消" @click="$router.push('/')" />
                </td>
            </tr>
        </table>
    </form>
</template>

<script setup>
import { ref } from "vue"
import { useRouter } from "vue-router"
import axios from "axios"

const router = useRouter()

// 后端 api
const api = "http://localhost:8000/books"

// 图书信息
const book = ref({
    bookName: '',
    autor: '',
    price: ''
})

// 新增
async function add() {
    for (const key in book.value) {
        if (book.value[key] === '') {
            return
        }
    }

    const data = await axios.post(api, book.value)
    if (data.data.code === 200) {
        router.push("/")
    }
}
</script>